import React, { PureComponent } from 'react';
import { Card, Form, Button, message } from 'antd';
import router from 'umi/router';
import { ExportOutlined } from '@ant-design/icons';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { connect } from 'dva';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoTable from '@/components/common/PateoTable';
import styles from '@/components/common/PateoTable/TableList.less';
import Ellipsis from '@/components/Ellipsis';
import * as G from '@/utils/common';
import { stringify } from 'qs';
import { getToken, getKeyValueString, getMd5 } from '@/utils/utils';
import { fingerprintFetch } from '@/utils/request'

const mapStateToProps = (state) => ({
  basedata: state.basedata,
  digitalKeyModelsGroup: state.digitalKeyModelsGroup,
  loading: state.loading.effects['digitalKeyModelsGroup/getFetchPage'],
  menu: state.menu,
});

class DigitalKeyModelsGroupDetail extends PureComponent {
  constructor(props) {
    super(props);
    const {
      location: { query },
      dispatch,
    } = this.props;
    if (!query) {
      router.push({
        pathname: '/bluetoothCloseControl/digitalKeyModelsGroup',
      });
      return;
    }
    const { brandCode, code, seriesCode } = query;
    this.state = {
      formValues: { brandCode, code, seriesCode }, //查询条件
      brandOptions: [],
      seriesOptions: query?.seriesOptions, // 车系的下拉列表
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res) => {
        this.setState({ brandOptions: res?.data }, () => {
          this.search.current?.setFieldsValue(formValues);
          this.handleFlushPage();
        });
      },
    });
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'digitalKeyModelsGroup/initData',
    });
  }
  //页面刷新
  handleFlushPage() {
    const { dispatch } = this.props;
    const { formValues, brandOptions } = this.state;

    const params = {
      ...formValues,
    };
    if (!params.brandCode) params.brandCode = brandOptions.map((o) => o.brandCode)?.join(',');
    dispatch({
      type: 'digitalKeyModelsGroup/getFetchPage',
      payload: { url: '/bluetooth/key/group/itemList', ...params },
    });
  }

  // 按品牌选车系
  onBrandSelect = (value) => {
    const { dispatch } = this.props;
    this.setState({ seriesOptions: [] });
    this.search.current?.setFieldsValue({ seriesCode: undefined });
    if (!value) {
      return;
    }
    dispatch({
      type: 'basedata/seriesList',
      payload: { brandId: value },
      callback: (response) => {
        if (response) {
          this.setState({
            seriesOptions: response.filter((item) => item.code !== ''),
          });
        }
      },
    });
  };

  handleFieldsValue = (fields) => {
    const { brandOptions } = this.state;
    if (G.isEmptyOrNil(fields['brandCode'])) {
      fields['brandCode'] = brandOptions.map((o) => o.brandCode)?.join(',');
    }
    return { ...fields };
  };
  handleExport = () => {
    const { formValues, brandOptions } = this.state;
    this.setState({ expButtonLoading: true });
    const params = {
      ...formValues,
    };
    if (!params.brandCode) params.brandCode = brandOptions.map((o) => o.brandCode)?.join(',');

    const str = `${window.g.url}/bluetooth/key/group/exportList?${stringify(params)}`;
    const newOptions = {};
    const md5 = getMd5(decodeURIComponent(stringify(params)));
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then((response) => {
        if (response.status === 200) {
          return response.blob();
        } else {
          this.setState({ expButtonLoading: false });
          throw response;
        }
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `蓝牙钥匙车型组明细.xls`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.setState({ expButtonLoading: false });
      })
      .catch(() => {
        this.setState({ expButtonLoading: false });
        message.error('导出失败，请稍后在试!');
      });
  };
  render() {
    const {
      digitalKeyModelsGroup: {
        pageData: { rows, pagination },
      },
      loading,
      dispatch,
      location: { pathname = '/' },
      menu: { permissions },
    } = this.props;
    const { formValues, brandOptions, seriesOptions } = this.state;
    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        key: 'brandCode',
        keyValue: ['brandCode', 'brandName'],
        selectOptions: brandOptions,
        onChange: (e) => {
          this.onBrandSelect(e);
        },
      },
      {
        title: '车系',
        type: 'select',
        key: 'seriesCode',
        keyValue: ['code', 'name'],
        selectOptions: seriesOptions,
      },
      {
        title: '钥匙车型组编码',
        type: 'input',
        key: 'code',
      },
      {
        title: '关联车型编码',
        type: 'input',
        key: 'modelCode',
      },
    ];
    const columns = [
      {
        title: '品牌',
        dataIndex: 'brandName',
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
      },
      {
        title: '钥匙车型组编码',
        dataIndex: 'groupCode',
        render: (text) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '钥匙车型组名称',
        dataIndex: 'groupName',
        render: (text) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '关联车型编码',
        dataIndex: 'modelCode',
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        render: (text) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
    ];

    const paginationProps = {
      showSizeChanger: true, //每页显示多少条
      showQuickJumper: true, //输数字快捷跳转
      ...pagination,
      showTotal: () => {
        return <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>;
      }, //展示页码信息栏
    };

    // 页面需要的一些数据信息
    const tableProps = {
      columns: columns, //列表标题信息
      dataSource: rows, //要渲染的数据信息
      loading: loading, //设置加载的lodalind
      rowKey: (record) => {
        return record.sid;
      }, //接收每一行信息参数,设置每一行的key
      pagination: paginationProps, //分页信息,如果没有分页则为false
    };

    return (
      <div>
        <Card bordered={false}>
          {/* <PateoSearchNewForm
              ref={(search) => (this.search = search)}
              searchItems={searchItems}
              fetchUrl="digitalKeyModelsGroup/getFetchPage"
              payloadUrl={{ url: '/bluetooth/key/group/itemList' }}
              handleFieldsValue={this.handleFieldsValue}
              dispatch={dispatch}
              saveFormValues={(val) =>
                this.setState({ formValues: Object.assign(formValues, val) })
              }
              handleFormReset={() => this.setState({ formValues: {} })}
              params={{
                brandCode: brandOptions.map((o) => o.brandCode)?.join(','),
              }}
            /> */}
          <PateoSearchForm
            onRef={(search) => (this.search = search)}
            searchItems={searchItems}
            fetchParams={{
              type: 'digitalKeyModelsGroup/getFetchPage',
              url: '/bluetooth/key/group/itemList',
            }}
            handleFieldsValue={this.handleFieldsValue}
            dispatch={dispatch}
            saveFormValues={(val) => this.setState({ formValues: Object.assign(formValues, val) })}
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            <Button
              icon={<ExportOutlined />}
              type="primary"
              size="small"
              loading={this.state.expButtonLoading}
              onClick={this.handleExport}
            >
              导出
            </Button>
          </div>

          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            dispatch={dispatch}
            fetchParams={{
              type: 'digitalKeyModelsGroup/getFetchPage',
              url: '/bluetooth/key/group/itemList',
            }}
            formValues={formValues}
            currentName="curPage"
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(DigitalKeyModelsGroupDetail);
